<?php
// 加载通用文件
require_once __DIR__ . '/../common/autoload.php';

// 检查是否已安装
if (!file_exists(__DIR__ . '/../.installed')) {
    json_response(['success' => false, 'message' => '系统未安装'], 503);
}

// 检查是否为Ajax请求
if (empty($_SERVER['HTTP_X_REQUESTED_WITH']) || strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
    json_response(['success' => false, 'message' => '非法请求'], 403);
}

// 检查登录状态（在用户中心不需要检查，但在POS端需要）
if (strpos($_SERVER['HTTP_REFERER'] ?? '', '/POS/') !== false) {
    check_login();
}

// 获取操作类型
$action = isset($_GET['action']) ? $_GET['action'] : '';

// 如果是POST请求，从JSON请求体中获取数据
$data = [];
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $json_data = file_get_contents('php://input');
    $data = json_decode($json_data, true);
    if (isset($data['action'])) {
        $action = $data['action'];
    }
}

// 处理不同的操作
switch ($action) {
    case 'search':
        // 搜索会员信息（根据手机号或会员ID）
        searchMember();
        break;
    case 'list':
        // 获取所有会员列表
        if (!is_admin()) {
            json_response(['success' => false, 'message' => '没有权限执行此操作'], 403);
        }
        listMembers();
        break;
    case 'get':
        // 获取会员信息
        getMember();
        break;
    case 'add':
        // 添加会员
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            json_response(['success' => false, 'message' => '请求方法不正确'], 405);
        }
        addMember($data);
        break;
    case 'update':
        // 更新会员信息
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            json_response(['success' => false, 'message' => '请求方法不正确'], 405);
        }
        updateMember($data);
        break;
    case 'recharge':
        // 会员充值
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            json_response(['success' => false, 'message' => '请求方法不正确'], 405);
        }
        rechargeMember($data);
        break;
    default:
        json_response(['success' => false, 'message' => '未知操作'], 400);
        break;
}

/**
 * 检查当前用户是否是管理员
 * @return bool
 */
function is_admin() {
    $current_user = current_user();
    return $current_user && $current_user['role'] === 'admin';
}

/**
 * 通过手机号或ID搜索会员
 */
function searchMember() {
    $phone = isset($_GET['phone']) ? trim($_GET['phone']) : '';
    $id = isset($_GET['id']) ? intval($_GET['id']) : 0;
    
    if (!$phone && !$id) {
        json_response(['success' => false, 'message' => '请提供手机号或会员ID'], 400);
    }
    
    // 构建查询条件
    $where = '';
    $params = [];
    
    if ($phone) {
        $where = "phone = ?";
        $params[] = $phone;
    } else {
        $where = "id = ?";
        $params[] = $id;
    }
    
    // 添加会员角色条件
    $where .= " AND role = 'member'";
    
    // 查询会员信息
    $member = Database::fetch("SELECT id, name, phone, email, balance, points FROM users WHERE $where", $params);
    
    if ($member) {
        json_response(['success' => true, 'member' => $member]);
    } else {
        json_response(['success' => true, 'member' => null]);
    }
}

/**
 * 获取会员列表
 */
function listMembers() {
    $page = isset($_GET['page']) ? intval($_GET['page']) : 1;
    $limit = isset($_GET['limit']) ? intval($_GET['limit']) : 20;
    $search = isset($_GET['search']) ? trim($_GET['search']) : '';
    
    // 确保页码和每页数量合法
    $page = max(1, $page);
    $limit = max(1, min(100, $limit));
    $offset = ($page - 1) * $limit;
    
    // 构建查询条件
    $where = ["role = 'member'"];
    $params = [];
    
    if ($search) {
        $where[] = "(name LIKE ? OR phone LIKE ? OR email LIKE ?)";
        $params[] = "%$search%";
        $params[] = "%$search%";
        $params[] = "%$search%";
    }
    
    $where_clause = implode(" AND ", $where);
    
    // 查询会员总数
    $total = Database::fetchColumn("SELECT COUNT(*) FROM users WHERE $where_clause", $params);
    
    // 查询会员列表
    $sql = "SELECT id, name, phone, email, balance, points, created_at 
            FROM users 
            WHERE $where_clause 
            ORDER BY created_at DESC 
            LIMIT $offset, $limit";
    $members = Database::fetchAll($sql, $params);
    
    json_response([
        'success' => true, 
        'members' => $members,
        'total' => $total,
        'page' => $page,
        'limit' => $limit
    ]);
}

/**
 * 获取会员信息
 */
function getMember() {
    $id = intval($_GET['id'] ?? 0);
    
    if ($id <= 0) {
        json_response(['success' => false, 'message' => '无效的会员ID'], 400);
    }
    
    $member = Database::fetch("SELECT * FROM users WHERE id = ? AND role = 'member'", [$id]);
    
    if (!$member) {
        json_response(['success' => false, 'message' => '会员不存在'], 404);
    }
    
    json_response([
        'success' => true, 
        'member' => $member
    ]);
}

/**
 * 添加会员
 * @param array $data 请求数据
 */
function addMember($data) {
    // 验证参数
    if (!isset($data['name']) || !isset($data['phone']) || !isset($data['password'])) {
        json_response(['success' => false, 'message' => '缺少必要参数'], 400);
    }
    
    $name = $data['name'];
    $phone = $data['phone'];
    $password = $data['password'];
    $username = $data['username'] ?? $phone;
    
    // 验证手机号
    if (!preg_match('/^1[3-9]\d{9}$/', $phone)) {
        json_response(['success' => false, 'message' => '手机号格式不正确'], 400);
    }
    
    // 检查手机号是否已存在
    $exists = Database::fetch("SELECT * FROM users WHERE phone = ?", [$phone]);
    if ($exists) {
        json_response(['success' => false, 'message' => '该手机号已注册'], 400);
    }
    
    // 检查用户名是否已存在
    $exists = Database::fetch("SELECT * FROM users WHERE username = ?", [$username]);
    if ($exists) {
        json_response(['success' => false, 'message' => '该用户名已被使用'], 400);
    }
    
    // 密码加密
    $encodedPassword = base64_encode($password);
    
    // 插入会员
    $memberId = Database::insert('users', [
        'username' => $username,
        'password' => $encodedPassword,
        'name' => $name,
        'phone' => $phone,
        'role' => 'member',
        'balance' => 0,
        'points' => 0
    ]);
    
    if (!$memberId) {
        json_response(['success' => false, 'message' => '添加会员失败'], 500);
    }
    
    // 获取会员信息
    $member = Database::fetch("SELECT * FROM users WHERE id = ?", [$memberId]);
    
    json_response([
        'success' => true, 
        'message' => '添加会员成功',
        'member' => $member
    ]);
}

/**
 * 更新会员信息
 * @param array $data 请求数据
 */
function updateMember($data) {
    // 验证参数
    if (!isset($data['id'])) {
        json_response(['success' => false, 'message' => '缺少必要参数'], 400);
    }
    
    $id = intval($data['id']);
    
    // 检查会员是否存在
    $member = Database::fetch("SELECT * FROM users WHERE id = ? AND role = 'member'", [$id]);
    if (!$member) {
        json_response(['success' => false, 'message' => '会员不存在'], 404);
    }
    
    // 准备更新数据
    $updateData = [];
    
    if (isset($data['name'])) {
        $updateData['name'] = $data['name'];
    }
    
    if (isset($data['phone'])) {
        $phone = $data['phone'];
        
        // 验证手机号
        if (!preg_match('/^1[3-9]\d{9}$/', $phone)) {
            json_response(['success' => false, 'message' => '手机号格式不正确'], 400);
        }
        
        // 检查手机号是否已被其他用户使用
        $exists = Database::fetch("SELECT * FROM users WHERE phone = ? AND id != ?", [$phone, $id]);
        if ($exists) {
            json_response(['success' => false, 'message' => '该手机号已被其他用户使用'], 400);
        }
        
        $updateData['phone'] = $phone;
    }
    
    if (isset($data['password']) && !empty($data['password'])) {
        $updateData['password'] = base64_encode($data['password']);
    }
    
    if (empty($updateData)) {
        json_response(['success' => false, 'message' => '没有需要更新的数据'], 400);
    }
    
    // 更新会员信息
    Database::update('users', $updateData, 'id = ?', [$id]);
    
    // 获取更新后的会员信息
    $member = Database::fetch("SELECT * FROM users WHERE id = ?", [$id]);
    
    json_response([
        'success' => true, 
        'message' => '更新会员信息成功',
        'member' => $member
    ]);
}

/**
 * 会员充值
 * @param array $data 请求数据
 */
function rechargeMember($data) {
    // 验证参数
    if (!isset($data['id']) || !isset($data['amount'])) {
        json_response(['success' => false, 'message' => '缺少必要参数'], 400);
    }
    
    $id = intval($data['id']);
    $amount = floatval($data['amount']);
    
    if ($amount <= 0) {
        json_response(['success' => false, 'message' => '充值金额必须大于0'], 400);
    }
    
    // 检查会员是否存在
    $member = Database::fetch("SELECT * FROM users WHERE id = ? AND role = 'member'", [$id]);
    if (!$member) {
        json_response(['success' => false, 'message' => '会员不存在'], 404);
    }
    
    // 计算新余额
    $newBalance = $member['balance'] + $amount;
    
    // 更新余额
    Database::update('users', ['balance' => $newBalance], 'id = ?', [$id]);
    
    // 获取更新后的会员信息
    $member = Database::fetch("SELECT * FROM users WHERE id = ?", [$id]);
    
    json_response([
        'success' => true, 
        'message' => '充值成功',
        'member' => $member
    ]);
} 